package com.yinhe.music.yhmusic.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.AppCache;
import com.yinhe.music.yhmusic.constants.Extras;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.PlayListDBEntity;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.utils.ToastUtils;

import java.io.File;


/**
 * 下载完成广播接收器
 * Created by hzwangchenyan on 2015/12/30.
 */
public class DownloadReceiver extends BroadcastReceiver {
    private PlayListDBEntity playListDBEntity;
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            playListDBEntity = DataBaseAccessor.getInstance().getSongBySongIdSyn(id);
            String title = AppCache.getDownloadList().get(id);
            if (TextUtils.isEmpty(title)) {
                return;
            }

            if (title.equals(Extras.DOWNLOAD_UPDATE)) {
                // 下载更新
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(id);
                Cursor cursor = manager.query(query);
                if (cursor == null) {
                    return;
                }


                int index = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);

                if (cursor.moveToFirst()) {
                    String uri = cursor.getString(index);
                    MLog.debug("DownReceiver","uri:"+uri);
                    if (!TextUtils.isEmpty(uri)){
                        String path = uri.replace("file://","");
                        MLog.debug("DownReceiver","path:"+path);
                        if (playListDBEntity!=null){
                            playListDBEntity.setUri(path);
                            DataBaseAccessor.getInstance().updateSong(playListDBEntity);
                        }
                        if (!TextUtils.isEmpty(path)) {
                            File file = new File(path);
                            if (file.exists()) {
                                install(context, file);
                            }
                        }
                    } else {
                        ToastUtils.show(R.string.update_fail);
                    }
                }
                cursor.close();
            } else {
                // 下载歌曲
                ToastUtils.show(context.getString(R.string.download_success, title));
            }
        } else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            // 点击通知取消下载
            long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            manager.remove(ids);
            ToastUtils.show("已取消下载");
        }
    }

    private void install(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(context, "com.yinhe.music.yhmusic.fileprovider", file);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(file);
        }

        intent.setDataAndType(data, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
